package database

import (
	"flag"
	"fmt"
	"gitee.com/mootok/mootok/src/constant/config"
	"gitee.com/mootok/mootok/src/utils/logging"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

var Client *gorm.DB

func init() {
	logger := logging.LogService("Gorm.Init")
	var err error
	var cfg gorm.Config
	var dsn = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		config.EnvConfig.MySqlUser,
		config.EnvConfig.MySqlPassword,
		config.EnvConfig.MySqlHost,
		config.EnvConfig.MySqlPort,
		config.EnvConfig.MySqlDatabase)

	if flag.Lookup("test.v") != nil {
		logger.Info("skip gorm init in testing mode")
		return
	}

	Client, err = gorm.Open(mysql.Open(dsn), &cfg)

	sqlDB, err := Client.DB()
	if err != nil {
		panic(err)
	}

	sqlDB.SetMaxIdleConns(100)
	sqlDB.SetMaxOpenConns(200)
	sqlDB.SetConnMaxLifetime(24 * time.Hour)
	sqlDB.SetConnMaxIdleTime(time.Hour)

}
